//
//  MineController.swift
//  SCA
//
//  Created by tjun on 2025/9/1.
//

import UIKit


enum MineCellType {
    case matrix
    case referralNetwork
    case buyPower
    case manualGuide
    case redeemPrizes
    case benefits
    case oneClickRegistration
    case commitmentChallenge
    case secondaryPassword
    case bindAccount
    case unbindAccount
    case authenticatorBinding
    case language
    case referrers
    case changePassword
    case logout
}

struct MineCellModel {
    let iconName: String
    let text: String
    let type: MineCellType
}

struct MineSectionCellModel {
    let title: String
    let datas: [MineCellModel]
}

class MineCell: BaseCollectionViewCell {
    
    private let textLabel = UILabel(font: UIFontMake(12), textColor: .white, textAlignment: .center)
    private let imageView = UIImageView()
    
    var model: MineCellModel! {
        didSet {
            textLabel.text = model.text
            imageView.image = UIImage(named: model.iconName)
        }
    }
    
    override func setSubView() {
        super.setSubView()
        
        
        imageView.addTo(contentView)
        
        imageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        textLabel.addTo(contentView)
        textLabel.numberOfLines = 2
        textLabel.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(5)
            make.width.equalToSuperview()
        }
        
    }
    
}


class MineSectionHeaderView: UICollectionReusableView {
    

    let textLabel = UILabel(font: UIFontMediumMake(16), textColor:UIColor.white)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = AppStyle.color.background
        
        addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class MineController: BaseController {
    
    private lazy var datas: [MineSectionCellModel] = [
        MineSectionCellModel(title: "捷径".localizedString, datas: [
            MineCellModel(iconName: "mine_matrix", text: "我的矩阵".localizedString, type: .matrix),
            MineCellModel(iconName: "referralNetwork", text: "引荐网".localizedString, type: .referralNetwork),
            MineCellModel(iconName: "buyPower", text: "熔铸算力".localizedString, type: .buyPower),
            MineCellModel(iconName: "manualGuide", text: "手册指南".localizedString, type: .manualGuide),
            MineCellModel(iconName: "redeemPrizes", text: "兑奖".localizedString, type: .redeemPrizes),
            MineCellModel(iconName: "operationManual", text: "一键注册".localizedString, type: .oneClickRegistration),
            MineCellModel(iconName: "benefits", text: "我的福利".localizedString, type: .benefits),
            MineCellModel(iconName: "commitmentChallenge", text: "承诺挑战".localizedString, type: .commitmentChallenge),
        ]),
        MineSectionCellModel(title: "设置".localizedString, datas: settingDatas)
    ]
    
    private var settingDatas: [MineCellModel] = [
        MineCellModel(iconName: "secondaryPassword", text: "设置二级安全密码".localizedString, type: .secondaryPassword)
    ]
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 50)
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        let itemSizeW = (view.width - layout.sectionInset.left - layout.sectionInset.right) / 4
        layout.itemSize = CGSizeMake(itemSizeW, itemSizeW + 2)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = AppStyle.color.background
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.alwaysBounceVertical = true
        collectionView.register(MineCell.self, forCellWithReuseIdentifier: MineCell.identifier)
        collectionView.register(MineSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                                withReuseIdentifier: MineSectionHeaderView.identifier)
        return collectionView
    }()
    
    private let slideTransitioningDelegate = SlideInTransitioningDelegate()

    private let levelImageView = UIImageView()
    
    func showInController( _ controller: UIViewController) {
        let nav = NavigationController(rootViewController: self)
        nav.modalPresentationStyle = .custom
        nav.transitioningDelegate = slideTransitioningDelegate
        controller.present(nav, animated: true)
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        modalPresentationStyle = .custom
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBarUI()
        reloadData()
    }
    
    private func setNavigationBarUI() {
        
        navigationBar.title = nil
        
        let closeButton = UIButton(type: .system)
        closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
        closeButton.tintColor = .white
        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        navigationBar.contentView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        let infoView = UIView()
        infoView.addSubview(levelImageView)
        levelImageView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalToSuperview().offset(-5)
            make.height.width.equalTo(70)
        }
        
        let accountNameLabel = UILabel(text: UserInfo.username, font: UIFontSemiboldMake(16), textColor: .white).addTo(infoView)
        accountNameLabel.snp.makeConstraints { make in
            make.left.equalTo(levelImageView.snp.right)
            make.top.equalTo(levelImageView).offset(16)
        }
        
        let switchAccountsButton = GradientButton(title: "切换账号".localizedString, font: UIFontMediumMake(12),  textColor: .white, target: self, action: #selector(switchAccountsButtonTapped))
        switchAccountsButton.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
        switchAccountsButton.locations = [0, 0.66, 1]
        switchAccountsButton.setStartPoint(CGPoint(x: 0, y: 0.5), endPoint: CGPointMake(1, 0.5))
        switchAccountsButton.isGradientBorder = false
        switchAccountsButton.layer.cornerRadius = 5
        switchAccountsButton.layer.masksToBounds = true
        infoView.addSubview(switchAccountsButton)
        switchAccountsButton.sizeToFit()
        switchAccountsButton.snp.makeConstraints { make in
            make.left.equalTo(accountNameLabel)
            make.bottom.equalTo(levelImageView)
            make.width.equalTo(switchAccountsButton.width + 20)
            make.height.equalTo(switchAccountsButton.height - 6)
        }
        
        let qrCodeButton = UIButton(image: UIImage(named: "qr-code"), target: self, action: #selector(qrCodeButtonTapped))
        infoView.addSubview(qrCodeButton)
        qrCodeButton.snp.makeConstraints { make in
            make.right.equalTo(-30)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        let lineView = UIView().addTo(infoView)
        lineView.backgroundColor = UIColor.gray.withAlphaComponent(0.5)
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(30)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
        let headerHeight: CGFloat = 90
        infoView.frame = CGRect(x: 0, y: -headerHeight, width: view.bounds.width, height: headerHeight)
        collectionView.addSubview(infoView)
        collectionView.contentInset = UIEdgeInsets(top: headerHeight, left: 0, bottom: 0, right: 0)
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(navBarHeight)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    @objc func closeButtonTapped() {
        dismiss(animated: true)
    }
    
    @objc func qrCodeButtonTapped() {
        let qrCodeController = QrCodeController()
        navigationController?.pushViewController(qrCodeController, animated: true)
    }
    
    @objc func switchAccountsButtonTapped() {
        NotificationCenter.default.post(name: NotificationName.userLogout, object: nil)
    }
    
    override var hiddenBackButton: Bool {
        return true
    }
    
    private func loadData() {
        MineService.loadUserData(success: { userModel in
            self.reloadData()
        })
    }
    
    private func reloadData() {
        
        let userInfoModel = UserInfoModel.current
        
        levelImageView.setImage(url: userInfoModel.levelIcon)
        
        if userInfoModel.canBind {
            settingDatas.append(MineCellModel(iconName: "mine_bindAccount", text: "绑定账号".localizedString, type: .bindAccount))
        }
        if userInfoModel.canUnbind {
            settingDatas.append(MineCellModel(iconName: "unbindAccount", text: "解除绑定账号".localizedString, type: .unbindAccount))
        }
        
        if !userInfoModel.isSet2fa {
            settingDatas.append(MineCellModel(iconName: "mine_2FAAuthenticatorBinding", text: "2FA验证器绑定".localizedString, type: .authenticatorBinding))
        }
        
        if !userInfoModel.isSetReferrer {
            settingDatas.append(MineCellModel(iconName: "mine_matrix", text: "设置引荐人".localizedString, type: .referrers))
        }
        
        settingDatas.append(contentsOf: [
            MineCellModel(iconName: "mine_changePassword", text: "更改密码".localizedString, type: .changePassword),
            MineCellModel(iconName: "mine_language", text: "语言".localizedString, type: .language),
            MineCellModel(iconName: "mine_logout", text: "登出".localizedString, type: .logout)
        ])
        
        collectionView.reloadData()
    }
}


extension MineController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas[section].datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = datas[indexPath.section].datas[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MineCell.identifier, for: indexPath) as! MineCell
        cell.model = model
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: MineSectionHeaderView.identifier, for: indexPath) as! MineSectionHeaderView
        let sectionModel = datas[indexPath.section]
        header.textLabel.text = sectionModel.title
        return header
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        let model = datas[indexPath.section].datas[indexPath.row]
        
        if model.type == .logout {
            NotificationCenter.default.post(name: NotificationName.userLogout, object: nil)
            return
        }
        
        if model.type == .referrers {
            qrCodeButtonTapped()
            return
        }
        
        if model.type == .matrix {
            let mineMatrixController = MineMatrixController()
            mineMatrixController.title = model.text
            navigationController?.pushViewController(mineMatrixController, animated: true)
            return
        }
        
        if model.type == .referralNetwork {
            let referralNetworkController = ReferralNetworkController()
            referralNetworkController.title = model.text
            navigationController?.pushViewController(referralNetworkController, animated: true)
            return
        }
        
        if model.type == .benefits {
            let mineBenefitsController = MineBenefitsController()
            mineBenefitsController.title = model.text
            navigationController?.pushViewController(mineBenefitsController, animated: true)
            return
        }
        
        if model.type == .commitmentChallenge {
            let challengeListController = ChallengeListController()
            challengeListController.title = model.text
            navigationController?.pushViewController(challengeListController, animated: true)
            return
        }
        
        if model.type == .bindAccount {
            let bindAccountController = BindAccountController()
            bindAccountController.title = model.text
            navigationController?.pushViewController(bindAccountController, animated: true)
            return
        }
        
        if model.type == .changePassword {
            let modifyPasswordController = ModifyPasswordController()
            modifyPasswordController.title = model.text
            navigationController?.pushViewController(modifyPasswordController, animated: true)
            return
        }
        
        if model.type == .secondaryPassword {
            let modifySecondaryPasswordController = ModifySecondaryPasswordController()
            modifySecondaryPasswordController.title = model.text
            navigationController?.pushViewController(modifySecondaryPasswordController, animated: true)
            return
        }
        
        if model.type == .authenticatorBinding {
            let validatorBindingController = ValidatorBindingController()
            validatorBindingController.title = model.text
            navigationController?.pushViewController(validatorBindingController, animated: true)
            return
        }
        
        if model.type == .language {
            let selectLanguageController = SelectLanguageController()
            present(selectLanguageController, animated: false)
            return
        }
        
        if model.type == .manualGuide {
            self.dismissToRootViewController(animated: true)
            guard let tabBarController = getRootController() as? UITabBarController,
                  let newsNavController = tabBarController.viewControllers?[2] as? NavigationController,
                  let newsController = newsNavController.topViewController as? NewsController
            else {
                return
            }
            tabBarController.selectedIndex = 2
            newsController.selectedIndex = 1
            return
        }
        
        if model.type == .buyPower {
            self.dismissToRootViewController(animated: true)
            guard let tabBarController = getRootController() as? UITabBarController,
                  let newsNavController = tabBarController.viewControllers?[1] as? NavigationController,
                  let computingPowerController = newsNavController.topViewController as? ComputingPowerController
            else {
                return
            }
            tabBarController.selectedIndex = 1
            let purchasePowerListController = PurchasePowerListController()
            computingPowerController.navigationController?.pushViewController(purchasePowerListController, animated: false)
            return
        }
        
        
        if model.type == .redeemPrizes {
            let redeemPrizeController = RedeemPrizeController()
            redeemPrizeController.title = model.text
            navigationController?.pushViewController(redeemPrizeController, animated: true)
            return
        }
        
        if  model.type == .oneClickRegistration ||
            model.type == .benefits ||
            model.type == .unbindAccount {
            
            let alert = Alert.alert(title: "温馨提示", message: "努力制作中", preferredStyle: .alert)
            alert.addAction(title: "Ok") {}.showIn(self)
            return
        }
        
    }
    
    
}
